package de.tsajar.es.networking.serializer;

import com.jme3.network.serializing.Serializer;
import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Serializer for Class objects
 * @author Eike Foede
 */
public class ClassSerializer extends Serializer {

    @Override
    public <T> T readObject(ByteBuffer data, Class<T> c) throws IOException {
        if (c.isAssignableFrom(Class.class)) {
            try {
                return (T) Class.forName((String) Serializer.readClassAndObject(data));
            } catch (ClassNotFoundException ex) {
                throw new IOException("Class not found!");
            }
        } else {
            throw new IOException("Requested object is no Class!");
        }

    }

    @Override
    public void writeObject(ByteBuffer buffer, Object object) throws IOException {
        if (object instanceof Class) {
            Class c = (Class) object;
            Serializer.writeClassAndObject(buffer, c.getName());
        } else {
            throw new IOException("Supported object is no Class!");
        }
    }
}
